using B.S.XZYData.Api.Read.Application.Command.DefectiveItemDistribution;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.DefectiveItemDistribution
{
    /// <summary>
    /// 获取不良品项分布分页数据处理器
    /// </summary>
    public class GetDefectiveItemDistributionHandler : IRequestHandler<GetDefectiveItemDistributionCommand, ApiPageing<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>>
    {
        private readonly MyDbContext _dbContext;

        public GetDefectiveItemDistributionHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiPageing<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>> Handle(GetDefectiveItemDistributionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询条件
                var query = _dbContext.Queryable<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>()
                    .Where(x => !x.IsDeleted);

                // 时间范围查询
                if (request.StartTime.HasValue)
                {
                    query = query.Where(x => x.Time >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(x => x.Time <= request.EndTime.Value);
                }

                // 不良品项编号查询
                if (!string.IsNullOrEmpty(request.DefectiveItemCode))
                {
                    query = query.Where(x => x.DefectiveItemCode.Contains(request.DefectiveItemCode));
                }

                // 不良品项名称查询
                if (!string.IsNullOrEmpty(request.DefectiveItemName))
                {
                    query = query.Where(x => x.DefectiveItemName.Contains(request.DefectiveItemName));
                }

                // 按时间倒序排列
                query = query.OrderByDescending(x => x.Time);

                // 获取总数
                var totalCount = await query.CountAsync();

                // 计算总页数
                var totalPage = (int)Math.Ceiling((double)totalCount / request.Size);

                // 分页查询
                var pageData = await query
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToListAsync();

                return new ApiPageing<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>
                {
                    TotaCount = totalCount,
                    TotaPage = totalPage,
                    PageData = pageData
                };
            }
            catch (Exception ex)
            {
                // 记录异常日志
                System.Diagnostics.Debug.WriteLine($"获取不良品项分布数据异常: {ex.Message}");
                
                return new ApiPageing<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>
                {
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = new List<B.S.XZYData.Domain.XZY.DefectiveItemDistribution>()
                };
            }
        }
    }
}
